package com.java.simple.study.juc.p7;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;

/**
 * @author zhoujunlin
 * @date 2022年10月09日 22:04
 * @desc
 */
@Slf4j(topic = "c.TestSemaphore")
public class TestSemaphore {

    /**
     * 22:07:53.519 c.TestSemaphore [Thread-1] - running...
     * 22:07:53.519 c.TestSemaphore [Thread-0] - running...
     * 22:07:53.519 c.TestSemaphore [Thread-2] - running...
     * 22:07:54.536 c.TestSemaphore [Thread-2] - end...
     * 22:07:54.536 c.TestSemaphore [Thread-0] - end...
     * 22:07:54.536 c.TestSemaphore [Thread-1] - end...
     * 22:07:54.536 c.TestSemaphore [Thread-3] - running...
     * 22:07:54.536 c.TestSemaphore [Thread-4] - running...
     * 22:07:54.536 c.TestSemaphore [Thread-5] - running...
     * 22:07:55.548 c.TestSemaphore [Thread-5] - end...
     * 22:07:55.548 c.TestSemaphore [Thread-4] - end...
     * 22:07:55.548 c.TestSemaphore [Thread-3] - end...
     * 22:07:55.548 c.TestSemaphore [Thread-6] - running...
     * 22:07:55.548 c.TestSemaphore [Thread-7] - running...
     * 22:07:55.548 c.TestSemaphore [Thread-8] - running...
     * 22:07:56.558 c.TestSemaphore [Thread-8] - end...
     * 22:07:56.558 c.TestSemaphore [Thread-7] - end...
     * 22:07:56.558 c.TestSemaphore [Thread-6] - end...
     * 22:07:56.558 c.TestSemaphore [Thread-9] - running...
     * 22:07:57.563 c.TestSemaphore [Thread-9] - end...
     *
     * @param args
     */
    public static void main(String[] args) {
        // 1. 创建Semaphore对象
        Semaphore semaphore = new Semaphore(3);

        // 2. 10个线程同时运行
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                // 3. 获取许可
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    log.debug("running...");
                    Sleeper.sleep(1);
                    log.debug("end...");
                } finally {
                    // 4. 释放许可
                    semaphore.release();
                }
            }).start();
        }

    }

}
